<template>
  <div>
    <el-card shadow="hover" class="layout-padding-auto">
      <TableSearch
        :search="state.search"
        @search="onSearch"
        @listenClick="listenClick"
      />
      <Table
        ref="tableRef"
        v-bind="state.tableData"
        class="table-demo"
        @delRow="onTableDelRow"
        @pageChange="onTablePageChange"
        @listenClick="listenClick"
      >
        <template #default="{ slotData, slotColumn }">
          <div v-if="slotColumn.key === 'roleType'"></div>
        </template>
      </Table>
      <!-- <PurveyorDialog :dialogVisible="dialogVisible" :dialogForm="dialogForm" :dialogDetail="dialogDetail"
        @cancel="cancel" @submit="submit">
      </PurveyorDialog> -->
      <DeviceTypeDialog
        :dialogVisible="dialogVisible"
        :dialogForm="dialogForm"
        :dialogDetail="dialogDetail"
        @cancel="cancel"
        @submit="submit"
      >
      </DeviceTypeDialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ref,
  reactive,
  defineAsyncComponent,
  onBeforeUnmount,
  onMounted
} from 'vue'
import { TableDemoPageType } from '/@/types/views'
import { deleteDeviceModel } from '/@/api/setting/index'
import routes from '/@/router'
import emitter from '/@/utils/mitt'
import { Session } from '/@/utils/storage'
import { buttonDisplayOrNot } from '../../../utils/buttonBoolean'
import { getButtonListByRoleApi } from '/@/api/publicApi'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const DeviceTypeDialog = defineAsyncComponent(
  () => import('./DeviceTypeDialog.vue')
)

const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = {
  width: '25%',
  title: ''
}

//定义变量内容
const tableRef = ref<RefType>()
const state = reactive<any>({
  tableData: {
    flash: false, //刷新表格
    //表头内容（必传，注意格式）
    header: [{ key: 'modelName', colWidth: '', title: '型号', type: 'text' }],
    columnBtn: [
      {
        name: 'editRole',
        text: '编辑',
        color: '#1962E0',
        btns: buttonCodes.value,
        btnCode: 'dataEditBtn'
      },
      {
        name: 'delRole',
        text: '删除',
        type: 'danger',
        btns: buttonCodes.value,
        btnCode: 'dataDeleteBtn'
      }
    ],
    //配置项（必传）
    config: {
      listApi: '/device/mobile/deviceModel/deviceModelList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      operateWidth: 460, //操作表格宽度,不传默认200
      isExtend: false // 是否可以扩展
    },
    // 搜索参数
    param: {
      deviceType: '-' as any
      // type: 1 // 必传参数，分页的不要传
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入设备型号搜索',
        type: 'input'
      }
    ],
    btn: [
      {
        text: '新增',
        fun: 'addRole',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'dataAddBtn'
      }
    ]
  }
})

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  // console.log(state.tableData.param);
  getTableData()
}

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}

//删除当前项回调
const onTableDelRow = (row: EmptyObjectType) => {
  ElMessage.success(`删除${row.name}成功!`)
  getTableData()
}

//分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const dialogDetail = ref<any>({})
//新增角色弹框
const addRole = () => {
  dialogDetail.value = { deviceType: state.tableData.param.deviceType }
  dialogForm.title = '添加'
  dialogVisible.value = !dialogVisible.value
}
//编辑角色弹框
const editRole = (row: any) => {
  dialogForm.title = '编辑'
  dialogDetail.value = row
  dialogVisible.value = !dialogVisible.value
}
//删除角色弹框
const delRole = (row: any) => {
  ElMessageBox.confirm('是否删除此型号?', '删除型号', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteDeviceModel(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

const cancel = () => {
  dialogVisible.value = !dialogVisible.value
}
const submit = () => {
  dialogVisible.value = !dialogVisible.value
  getTableData()
}

// 获取当前点击的树节点
emitter.on('deviceCurrentNode' as any, (node) => {
  state.tableData.param.deviceType = node.id
  getTableData()
})

onBeforeUnmount(() => {
  emitter.off('deviceCurrentNode' as any)
})

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  addRole: addRole,
  editRole: editRole,
  delRole: delRole
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/setting/Dictionaries') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>

<style scoped lang="scss"></style>
